<?php
namespace Api\Dbal\Doctrine;

use Api\Application;
use Doctrine\Common\Cache\ApcCache;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;

/**
 * Class Doctrine
 * @package Api\Dbal\Doctrine
 * @author Steffen Brem <steffenbrem@gmail.com>
 */
class Doctrine
{
    /**
     * @var \Api\Application
     */
    protected $application;

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->application = Application::$shared;

        require_once __DIR__ . "/vendor/autoload.php";

        if (!$this->application->config['doctrine']['entity_namespace'])
        {
            throw new \Exception("You must set an entity namespace in your settings.ini file.");
        }

        $path = $this->application->config['application']['path'] .
            DIRECTORY_SEPARATOR . $this->application->config['doctrine']['entity_path'] .
            DIRECTORY_SEPARATOR . $this->application->config['doctrine']['entity_namespace'];

        $this->application->autoloader->register($this->application->config['doctrine']['entity_namespace'], $path);

        $paths = array($path);
        $isDevMode = true;

        $settings = array(
            'host'      => $this->application->config['database']['host'],
            'driver'    => $this->application->config['database']['driver'],
            'user'      => $this->application->config['database']['user'],
            'password'  => $this->application->config['database']['password'],
            'dbname'    => $this->application->config['database']['dbname']
        );

        $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false);
        $config->setQueryCacheImpl(new ArrayCache());
        $config->setMetadataCacheImpl(new ArrayCache());

        $this->em = EntityManager::create($settings, $config);

        $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
    }

    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->em;
    }
}